var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

exports.setup = function(User, config) {
  passport.use(new LocalStrategy({
      usernameField: 'code',
      passwordField: 'namepass' // this is the virtual field on the model
    },
    function(code, namepass, done) {
      User.findOne({
        code: code
      }, function(err, user) {
        if (err) return done(err);

        if (!user) {
          return done(null, false, {
            message: '用户代码不存在.'
          });
        }
        var name = namepass.substr(0, namepass.indexOf('#'));
        if (user.name !== name) {
          return done(null, false, {
            message: '用户姓名错误.'
          });
        }
        //console.log("user.password:", user.password);
        if (!user.password) {
          return done(null, user);
        }
        var pass = namepass.substr(namepass.indexOf('#') + 1);
        if (!pass) {
          return done(null, false, {message: 'needpass'});
        }
        if (!user.authenticate(pass)) {
          return done(null, false, {message: '密码错误.'});
        }
        return done(null, user);
      });
    }
  ));
};
